using Luban;
using System;
using System.Collections.Generic;
using UnityEngine;
using YooAsset;

namespace LFramework
{
    /// <summary>
    /// 数据表管理器
    /// </summary>
    public class DataTableManager : IDisposable
    {
        private Dictionary<Type, IDataConfig> m_DataCofnigDic = null;

        public DataTableManager() 
        {
            m_DataCofnigDic = new();
        }

        public void Init() 
        {
            
        }

        public T GetDataConfig<T>(string address) where T : class
        {
            IDataConfig dataConfig = null;
            if (!m_DataCofnigDic.TryGetValue(typeof(T), out dataConfig)) 
            {
                T config = ResolveDataConfig<T>(address);
                dataConfig = new DataConfig<T>(config);
                m_DataCofnigDic[typeof(T)] = dataConfig;
            }
            return (dataConfig as DataConfig<T>).GetConfig();
        }

        private T ResolveDataConfig<T>(string address) where T : class
        {
            TextAsset textAsset = LoadTextAsset(address);

            var configInstance = Activator.CreateInstance(typeof(T), new ByteBuf(textAsset.bytes)) as T;
            return configInstance;
        }

        private TextAsset LoadTextAsset(string address)
        {
            AssetHandle handle = YooAssets.LoadAssetSync<TextAsset>(address);
            TextAsset textAsset = handle.AssetObject as TextAsset;
            handle.Release();
            return textAsset;
        }

        public void Dispose()
        {
            m_DataCofnigDic.Clear();
            m_DataCofnigDic = null;
        }
    }
}